<?php
/**
 * Created by PhpStorm.
 * User: 张辉
 * Date: 2018/6/19
 * Time: 10:56
 */
namespace app\common\service;
use Illuminate\Support\Facades\Storage;
use Melihovv\Base64ImageDecoder\Base64ImageDecoder;
use Melihovv\Base64ImageDecoder\Exceptions\InvalidFormat;

/**
 * Class imgBase64Upload   上传base64图片类
 * @package app\common\library
 */
class ImgBase64Upload
{
    /**
     * @var string 错误信息
     */
    public static $error = '';

    /**
     * 解析base64文件  返回文件路径
     * @param string $base64EncodedImage  base64字符串
     * @param string $imageType  文件类型
     * @return mixed
     */
    public static function upload( $base64EncodedImage, $imageType = 'default' )
    {
        $publicPath = WEB_UPLOADS;

        $filePath = [
            'default'   => 'default/PHP_UPLOAD/'.date('Y/m/d').'/',      // 默认存放位置
            'writer_thumbnail' => 'writer_thumbnail/PHP_UPLOAD/'.date('Y/m/d').'/',    //base64 临时存储位置
            'avatar'           => 'avatar/PHP_UPLOAD/'.date('Y/m/d').'/',      // 默认存放位置
        ];

        try{
            $decoder = new Base64ImageDecoder( $base64EncodedImage, $allowedFormats = ['jpg','jpeg', 'png', 'gif'] );
        }catch (  InvalidFormat $e ){
            self::$error = $e->getMessage();
            return false;
        }


        if ( !$decoder->getDecodedContent() ){
            self::$error = '解码错误';
            return false;
        }

        $fileName = uniqid().'.'.$decoder->getFormat();

        if ( !isset($filePath[$imageType]) ){
            $imageType = 'default';
        }


        $imageFilePath = $filePath[$imageType];

        if ( !is_dir($publicPath.$imageFilePath) ){
            if ( !mkdir( $publicPath.$imageFilePath, 0777 , true)  ){
                self::$error = '没有文件权限';
                return false;
            }
        }

        if ( !file_put_contents( $publicPath.$imageFilePath.$fileName, $decoder->getDecodedContent() ) ){
            self::$error = '上传失败';
            return false;
        }

        return array(
            'filename'	=>	$fileName,
            'virtual_path'	=>	$imageFilePath.$fileName,      // oss上传路径
            'absolute_path' =>	$publicPath.$imageFilePath.$fileName, // 项目绝对路径
        );

    }

    /**
     * base64图片传至oss
     * @param $base64EncodedImage
     * @param string $imageType
     */
    public static function up_oss(  $base64EncodedImage, $imageType = 'default' )
    {
        $path = self::upload( $base64EncodedImage, $imageType );

        if ( !$path ){
            return false;
        }
        // 上传阿里云OSS
        $Storage = new Storage( );
        $Storage->save_resource( $path['virtual_path'], $path['absolute_path'] );
        $path['preview_path'] = $Storage->url_prifix.$path['virtual_path'];
        return $path;

    }

}